<?php
include(__DIR__ . '/ck/global.php');

$zoneId = empty($_GET['id']) ? 0 : (int)$_GET['id'];

if (empty($zoneId)) {
    exit('e1');
}

if (!$zoneRecord = Zone::getById($zoneId)) {
    exit('e2');
}

if (empty($zoneRecord['ids'])) {
    exit('e3');
}

$tmp = array_shift($zoneRecord['ids']);

if (empty($tmp['ad_id'])) {
    exit('e4');
}

if (!$adRecord = Ad::getById($tmp['ad_id'])) {
    exit('e5');
}

$url          = ''; //跳转地址
$jsCode       = '';
/**
 * 安卓微信上没有isappinstalled参数？
 */
//$isFromWeiXin = (isset($_GET['from']) && isset($_GET['isappinstalled'])) ? 1 : 0;
$isFromWeiXin = (isset($_GET['from'])) ? 1 : 0;
$isFromWeiXin = 1;  //默认直接从微信来量

/**
 * 如果不是从微信来量，直接到达广告主网站
 */
if ($isFromWeiXin) {
    $time = time();
    $sign = get_to_g_sign($time);
    $host = trim(file_get_contents(__DIR__ . '/go.txt'));
    $url  = "http://{$host}:811/g.php?id={$zoneId}&time={$time}&sign={$sign}";
} else {
    $url = '';

    $device = PlanDevice::detect($_SERVER['HTTP_USER_AGENT']);

    $urlKey = 'url_' . $device;
    $url    = empty($adRecord[$urlKey]) ? '' : $adRecord[$urlKey];

    /**
     * 如果没有找到对应终端网址，尝试查找微信网址
     */
    if (empty($url)) {
        $urlKey = 'url_4';
        $url    = empty($adRecord[$urlKey]) ? '' : $adRecord[$urlKey];
    }
}


if ($isFromWeiXin && !empty($url)) {
    $jsCode = <<<EOD
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Loading...</title>
<style>
* { padding:0; margin:0; }
h6 {
background:rgba(0,0,0,0.6);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align:center;
border-radius:10px;
color:#fff;
font-size:1.5rem;
padding:1rem .5rem;
}
</style>
</head>
<body>
<h6>正在载入...</h6>
<script>
(function(W, S, L, C){
C = W[S];
EOD;

    if ($isFromWeiXin) {
        $jsCode .= "L = [L, 'w=' + C.width, 'h=' + C.height, 'c=' + C.colorDepth].join('&');";
    }

    $jsCode .= <<<EOD
location.href = L;
})(window, 'screen', '{$url}');
</script>
</body>
</html>
EOD;

    exit($jsCode);
}

echo <<<EOD
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{$adRecord['zl_title']}</title>
</head>
<body>
{$jsCode}
<img src="{$adRecord['zl_img_url']}">
</body>
</html>
EOD;
